package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author 陈辉
 * @data 2023 11:50
 */
@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(TaskDto task) {
        //1. 将任务及任务日志保存到数据库中
        long taskId = IdWorker.getId();
        task.setTaskId(taskId);
        boolean success = addTaskToDB(task);

        //2. 将符合条件的任务添加到redis中
        if (success){
            addTaskToRedis(task);
        }
        return taskId;
    }

    /**
     * 拉取任务
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public TaskDto popTask(Integer taskType, Integer priority) {
        //1. 将任务从redis的list中取出
        String key = ScheduleConstants.TOPIC+taskType+"_"+priority;
        String taskJson = cacheService.lRightPop(key);
        TaskDto taskDto = JSON.parseObject(taskJson, TaskDto.class);

        //2. 将taskInfo删除
        if (taskDto != null) {
            taskinfoMapper.deleteById(taskDto.getTaskId());
            //3. 将taskInfoLogs修改
            TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskDto.getTaskId());
            logs.setStatus(ScheduleConstants.EXECUTED);
            taskinfoLogsMapper.updateById(logs);
        }
        return taskDto;
    }

    /**
     * 添加符合条件的任务到缓存
     * 1. 如果当前任务的执行时间 <= 当前系统时间： 将任务添加到List中
     * 2. 预设时间（当前时间+5分钟） >= 如果当前任务的执行时间 > 当前系统时间：
     *      将任务添加到ZSet中
     * @param task
     */
    private void addTaskToRedis(TaskDto task) {

        // String key = "1001_1"
        String key = task.getTaskType() +"_" +task.getPriority();
        //预设时间
        long zsetTime = System.currentTimeMillis() + (1000 * 60 * 5);

        long executeTime = task.getExecuteTime();
        //1. 如果当前任务的执行时间 <= 当前系统时间： 将任务添加到List中
        if (executeTime <= System.currentTimeMillis()){
                                    //"topic_1001_1"
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if(executeTime > System.currentTimeMillis() && executeTime <= zsetTime){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addTaskToDB(TaskDto task) {
        boolean flag = false;

        try {
            //1. 先存入taskInfo
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //2. 再存入taskInfo_logs
            TaskinfoLogs logs = new TaskinfoLogs();
            BeanUtils.copyProperties(task,logs);
            logs.setExecuteTime(new Date(task.getExecuteTime()));
            logs.setVersion(1);
            logs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(logs);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }


    /**
     * redis定时刷新：
     *  每分钟刷新一次：将ZSet中符合条件的数据刷新到List中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis(){
        log.info("redis定时刷新：每分钟刷新一次：将ZSet中符合条件的数据刷新到List中...");
        //1. 取出ZSet中符合条件数据：getExecuteTime <= System.currentTimeMillins();
        Set<String> zSetKeys = cacheService.scan(ScheduleConstants.FUTURE+"*");  //{"future_1001_1"}
        for (String futureKey : zSetKeys) {   //futureKey: "future_1001_1"
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

            String key = futureKey.split(ScheduleConstants.FUTURE)[1];  //["","1001_1"]
            String topicKey = ScheduleConstants.TOPIC+key;  //topicKey: "topic_1001_1"
            //将符合条件的任务转移到list中
            // -- 1. 根据futureKey找到对应的ZSet,将里面对应的tasks删除
            // -- 2. 根据topicKey找到对应的list,将里面对应的tasks添加
            if (tasks != null && tasks.size() > 0 ) {
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
            }
        }
    }


    /**
     * DB中的任务定时刷新到redis：
     *  每5分钟刷新一次
     */
    @PostConstruct      //Bean的初始化方法：当bean被创建好后，会自动执行该方法，只执行一次！
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshDBToRedis(){
        //1. 清空redis中的任务
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);

        //2. 查询数据库中未来5分钟内的任务
        Date futureDate = new Date(System.currentTimeMillis() + (1000 * 60 * 5));
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, futureDate));

        //3. 将目标任务同步到redis
        for (Taskinfo taskinfo : taskinfos) {
            TaskDto dto = new TaskDto();
            BeanUtils.copyProperties(taskinfo,dto);
            dto.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTaskToRedis(dto);
        }
    }



}
